package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.WebSocket.WebSocketServer;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.service.ShoppingCartService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private WebSocketServer webSocketServer;

    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //处理业务异常,地址，购物车
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook == null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        Long userId= BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCart = shoppingCartMapper.querylist(userId);
        if(shoppingCart.isEmpty()){
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //插入订单
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setUserId(userId);
        orders.setAddress((addressBook.getProvinceName() + " " + addressBook.getCityName() + " " + addressBook.getDistrictName() + " " + addressBook.getDetail()));
        orders.setConsignee(addressBook.getConsignee());

        log.info("\norders:{}\n",orders);
        ordersMapper.insert(orders);
        List<OrderDetail> orderDetails = new ArrayList<>();
        //插入订单明细表
        for(ShoppingCart cart:shoppingCart){
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
            log.info("\norderDetail:{}\n",orderDetail);
        }
        log.info("\norderDetails:{}\n",orderDetails);
        orderDetailMapper.insertBatch(orderDetails);
        //清空购物车
        shoppingCartMapper.clean(userId);
        //封装返回结果
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO().builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = ordersMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
        //支付成功后向商家发送新的订单请求通知
        log.info("支付成功后向商家发送新的订单请求通知");
        Map map=new HashMap();
        map.put("type",1);//1表示新订单
        map.put("orderId",orders.getId());
        map.put("context","订单号:"+outTradeNo);//订单号
        String json= JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);

    }

    @Override
    @Transactional
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        log.info("分页查询订单");
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Page<Orders> page = ordersMapper.pageQuery(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList<>();
        if(page!=null&&page.getResult().size()>0);{
            for(Orders order:page){
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(order,orderVO);
                List<OrderDetail> orderDetails = orderDetailMapper.queryByOrderId(order.getId());
                orderVO.setOrderDetailList(orderDetails);
                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(),list);
    }

    @Override
    public OrderVO queryById(Long id) {
        Orders order = ordersMapper.getById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order,orderVO);
        List<OrderDetail> orderDetails = orderDetailMapper.queryByOrderId(order.getId());
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    //
    @Transactional
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        StringBuilder meg = new StringBuilder();
        Orders order = ordersMapper.getById(ordersCancelDTO.getId());
        log.info("\norder:{}\n", order);
        Integer status = order.getStatus();
        log.info("Order status: {}", status);
        if (Objects.equals(status, 2) || Objects.equals(status, 1)) {
            log.info("进入取消订单逻辑");
            order.setCancelTime(LocalDateTime.now());
            order.setCancelReason(ordersCancelDTO.getCancelReason());
            order.setStatus(6);
            ordersMapper.update(order);
            meg.append("订单取消成功");
        } else  if(Objects.equals(status, 3) || Objects.equals(status, 4)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

    }

    @Override
    public void repeation(Long id) {
        //重新设置购物车
        ShoppingCartDTO shoppingCartDTO = new ShoppingCartDTO();
        List<OrderDetail> orderDetails = orderDetailMapper.queryByOrderId(id);
        for(OrderDetail orderDetail:orderDetails){
            shoppingCartDTO.setDishFlavor(orderDetail.getDishFlavor());
            shoppingCartDTO.setDishId(orderDetail.getDishId());
            shoppingCartDTO.setSetmealId(orderDetail.getSetmealId());
            shoppingCartService.add(shoppingCartDTO);
        }
    }

    //条件搜索
    @Override
    public PageResult conditionSerch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> page = ordersMapper.pageQuery(ordersPageQueryDTO);
        List<OrderVO> list = getOrderVO(page);
        return new PageResult(page.getTotal(),list);
    }

    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(ordersMapper.countByStatus(Orders.CONFIRMED));
        orderStatisticsVO.setDeliveryInProgress(ordersMapper.countByStatus(Orders.DELIVERY_IN_PROGRESS));
        orderStatisticsVO.setToBeConfirmed(ordersMapper.countByStatus(Orders.TO_BE_CONFIRMED));
        return orderStatisticsVO;
    }

    @Override
    public OrderVO details(Long id) {
        Orders order = ordersMapper.getById(id);
        OrderVO orderVO = new OrderVO();
        String orderDishes= getOrderDishesStr(order);
        BeanUtils.copyProperties(order,orderVO);
        orderVO.setOrderDishes(orderDishes);
        orderVO.setOrderDetailList(orderDetailMapper.queryByOrderId(order.getId()));
        return orderVO;
    }

    //接单
    @Override
    public void confirm(Long id) {
        ordersMapper.adminUpdate(id, Orders.CONFIRMED);
    }

    //拒单
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders order = ordersMapper.getById(ordersRejectionDTO.getId());
        if(order.getStatus()==Orders.PENDING_PAYMENT){
            order.setStatus(Orders.CANCELLED);
        }
        if(order.getStatus()==Orders.TO_BE_CONFIRMED){
           order.setStatus(7);
        }
        order.setCancelTime(LocalDateTime.now());
        order.setCancelReason(ordersRejectionDTO.getRejectionReason());
        ordersMapper.update(order);
    }

    @Override
    public void delivery(Long id) {
        Integer status = ordersMapper.getById(id).getStatus();
        if(status==3){
            ordersMapper.adminUpdate(id, Orders.DELIVERY_IN_PROGRESS);
        }else{
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

    @Override
    public void complete(Long id) {
        Integer status = ordersMapper.getById(id).getStatus();
        if(status==4){
            ordersMapper.adminUpdate(id, Orders.COMPLETED);
        }else{
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
    }

    @Override
    public void remind(Long id) {
        Orders order = ordersMapper.getById(id);
        //如果下单时间超过15分钟
        if(order.getOrderTime().plusMinutes(15).isBefore(LocalDateTime.now())){
            Map map=new HashMap();
            map.put("type",2);//2为用户催单
            map.put("orderId",order.getId());
            map.put("context","您的订单已超过15分钟未处理，请尽快处理,订单号："+order.getNumber());
            String json= JSONObject.toJSONString(map);
            webSocketServer.sendToAllClient(json);
        }
    }

    //封装结果
    public List<OrderVO> getOrderVO(Page<Orders> page){
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }
    //获取订单信息字符串
    public String getOrderDishesStr(Orders orders){
        List<OrderDetail> orderDetailList = orderDetailMapper.queryByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    //错误实现，直接复制了订单并修改订单状态
//    @Override
//    public void repeation(Long id) {
//        Orders order = ordersMapper.getById(id);
//        Long orderOldId=order.getId();
//        order.setStatus(1);
//        //订单id会更新
//        ordersMapper.insert(order);
//        Long orderNewId=order.getId();
//        //更改订单明细表中·的id
//        List<OrderDetail> orderDetails = orderDetailMapper.queryByOrderId(orderOldId);
//        for(OrderDetail orderDetail:orderDetails){
//            orderDetail.setOrderId(orderNewId);
//            orderDetailMapper.insert(orderDetail);
//        }
//    }

}
